/*
 * user_json.c
 *
 *  Created on: 2018年9月19日
 *      Author: hongyun.he
 */
#include "gd32w51x.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include "cJSON.h"

#include "rtthread.h"

#include "version.h"
#include "DevicesCRC.h"
#include "DevicesFlash.h"
#include "DevicesDelay.h"
#include "DevicesRandom.h"
#include "DevicesUart.h"
#include "DevicesQueue.h"
#include "NesSystem.h"

#include "UserTask.h"
#include "UserJson.h"




int8_t cJsonCallbackNES(cJSON *pjsonRoot)
{
    cJSON *pcJsonItem[4] = {NULL};


    if((pcJsonItem[0] = cJSON_GetObjectItem(pjsonRoot, "state")) != NULL)
    {
        if(strcasecmp(pcJsonItem[0]->valuestring, "reset") == 0)
        {
            rt_thread_suspend(g_TaskSimulatorNESHand);
            cNesReset();
        }
        else if(strcasecmp(pcJsonItem[0]->valuestring, "start") == 0)
        {
            cNesStart();
            rt_thread_resume(g_TaskSimulatorNESHand);
        }
        else if(strcasecmp(pcJsonItem[0]->valuestring, "stop") == 0)
        {
            rt_thread_suspend(g_TaskSimulatorNESHand);
            cNesStop();
        }
    }

    if((pcJsonItem[0] = cJSON_GetObjectItem(pjsonRoot, "loadFile")) != NULL)
    {
        /* 从外部存储器加载NES文件到内存Flash（为了加快运行当中切换Bank的速度） */
        cNesFlashLoad(pcJsonItem[0]->valuestring);

        /* 从内部Flash加载NES固件到模拟器 */
        cNesLoad();
    }

    return 0;
}



jsonHookFunctionType ex_jsonHookFunctionGather[] =
{
    {
        "NES",
        cJsonCallbackNES,
    },
};


#define JSON_HOOK_FUNCTION_NUMBER (sizeof(ex_jsonHookFunctionGather) / sizeof(jsonHookFunctionType))


int8_t cJsonParser(char *pcJSONPrintUnformatted)
{
    cJSON *pjsonItem = NULL, *pjsonRoot = NULL;
    char *pucJSONPrintUnformatted = NULL;
    int8_t cError = 0, i = 0;


    pjsonRoot = cJSON_Parse(pcJSONPrintUnformatted);
    if(pjsonRoot == NULL)
    {
        printf("pcJSONPrintUnformatted cJSON_Parse error.\r\n");
        return -3;
    }


    /* 查找指令钩子函数 */
    for(i = 0; i < JSON_HOOK_FUNCTION_NUMBER; ++i)
    {
        if((pjsonItem = cJSON_GetObjectItem(pjsonRoot, ex_jsonHookFunctionGather[i].pcName)) != NULL)
        {
            /* 把指令与数据发送到解析函数 */
            cError |= ex_jsonHookFunctionGather[i].cJsonHookFunction(pjsonItem);

            break;
        }
    }

    pucJSONPrintUnformatted = cJSON_PrintUnformatted(pjsonRoot);

    /* 串口2发送 */
    vUartDMASendStrings(USART2, pucJSONPrintUnformatted);

    free(pucJSONPrintUnformatted);


    cJSON_Delete(pjsonRoot);


    return cError;
}

